package com.lmc.gobang.game;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class RoomManager {
    //表示房间id和房间的映射关系
    private ConcurrentHashMap<String,Room> rooms = new ConcurrentHashMap<>();
    //表示房间id和玩家的映射关系
    private ConcurrentHashMap<Integer,String> usersToRoom = new ConcurrentHashMap<>();

    public void add(Room room,int playerId1,int playerId2) {
        rooms.put(room.getRoomId(),room);
        usersToRoom.put(playerId1, room.getRoomId());
        usersToRoom.put(playerId2, room.getRoomId());
    }

    public void remove(String roomId,int playerId1,int playerId2) {
        rooms.remove(roomId);
        usersToRoom.remove(playerId1);
        usersToRoom.remove(playerId2);
    }

    public Room getRoom(String roomId) {
        return rooms.get(roomId);
    }

    public Room getRoomByPlayerId(int playerId) {
        String roomId = usersToRoom.get(playerId);
        if(roomId == null) {
            return null;
        }
        return rooms.get(roomId);
    }
}
